<?php

namespace app\admin\controller;

use app\BaseController;
use think\App;

/**
 * @author xjw
 * @class:TaskorderDispute 定时任务=>争议订单操作
 * @method order_dispute 争议订单操作
 * @method deal_orders_dispute 处理争议订单
 * @return  
 */


class Tasktransfer extends BaseController
{

    protected $model = null;

    public function __construct(App $app)
    {
        parent::__construct($app);
    }

    /**
     *  1.* 获取主题
     */
    public function transfer_themes()
    {
        $id = $this->request->request('id');
        $result = array();
        if (!empty($id)) {
            $site = table('site')
                ->where('id', $id)
                ->find();
            if ($site) {
                $result = $this->store_themes($site);
            }
        }
        return success('操作成功', $result);
    }

    public function store_themes($site)
    {
        $url = $site['site_url'] . "/admin/api/2023-07/themes.json";
        $data =  geturl($url, $site['apikey'], $site['apisecret']);
        $result = array();
        if ($data) {
            $data = json_decode($data, true);
            if (!empty($data['errors'])) {
                return $data['errors'];
            }
            $themes = $data['themes'];
            if (is_array($themes) && !empty($themes)) {
                //获取主题跟资产
                foreach ($themes as $theme) {
                    $transfer_themes = table('transfer_themes')->where('theme_id', $theme['id'])->find();
                    if (empty($transfer_themes)) {
                        $arr['accounturl'] = $site['id'];
                        $arr['theme_id'] = $theme['id'];
                        $arr['name'] = $theme['name'];
                        $arr['created_at'] = $theme['created_at'];
                        $arr['updated_at'] = $theme['updated_at'];
                        $arr['role'] = $theme['role'];
                        $arr['theme_store_id'] = $theme['theme_store_id'];
                        $arr['previewable'] = $theme['previewable'];
                        $arr['processing'] = $theme['processing'];
                        $arr['admin_graphql_api_id'] = $theme['admin_graphql_api_id'];
                        $arr['createtime'] = time();
                        $arr['updatetime'] = time();
                        // $result = table('transfer_themes')->insert($arr);
                        //                        if (!empty($result)) {
                        //                            $this->transfer_themes_asset($arr,$iscustom);
                        //                        }
                    }
                }
            }
        }
        return $result;
    }

    /**
     *  转移商品到新店铺
     */
    //  Tasktransfer/api_products_transfer?oldid=8&newid=101
    public function api_products_transfer()
    {
        $site_oldid = $this->request->request('oldid');
        $site_newid = $this->request->request('newid');
        $products = table('order_product')
            ->where('site_id', $site_oldid)
            ->where('transfer_status', 0)
            ->order('transfer_time asc')
            ->limit(10)
            ->select()->toarray();
        $returns = [];
        if (!empty($products)) {
            foreach ($products as $k=>$v) {
                $return = $this->accounturl_product3($v, $site_newid);
                $arr['transfer_time'] = time();
                $arr['transfer_status'] = $return;
                $returns[] = table('order_product')
                    ->where('id', $v['id'])
                    ->update($arr);
            }
        }
        return success('操作完成', $returns);
    }

    public function accounturl_product3($products_shopify, $params)
    {

        $msgs = 3;
        if (!empty($products_shopify)) {
            //先更新一遍再生成SKU
            $site = table('site')
                ->where('id', $products_shopify['site_id'])
                ->find();
            $url = $site['site_url'] . "/admin/api/2023-07/products/" . $products_shopify['product_id'] . ".json";
            $ldata =  geturl($url, $site['apikey'], $site['apisecret']);
            $larr = array();
            if ($ldata) {
                $ldata2 = json_decode($ldata, true);
                if (!empty($ldata2['errors'])) {
                    return 'A-'.$ldata2['errors'];
                }
                if (!empty($ldata2['product'])) {
                    $lproduct = $ldata2['product'];
                    $larr['title'] = $lproduct['title'];
                    $larr['body_html'] = $lproduct['body_html'];
                    $larr['vendor'] = $lproduct['vendor'];
                    $larr['product_type'] = $lproduct['product_type'];
                    $larr['tags'] = $lproduct['tags'];
                    $larr['status'] = $lproduct['status'];
                    $larr['variants'] = array();
                    $larr['options'] = array();
                    $larr['images'] = array();
                    if (!empty($lproduct['variants'])) {
                        foreach ($lproduct['variants'] as $kvariants => $vvariants) {
                            $avariants = array();
                            $avariants['option1'] = $vvariants['option1'];
                            $avariants['price'] = $vvariants['price'];
                            $avariants['sku'] = $vvariants['sku'];
                            $avariants['option1'] = $vvariants['option1'];
                            $avariants['option2'] = $vvariants['option2'];
                            $avariants['option3'] = $vvariants['option3'];
                            $larr['variants'][] = $avariants;
                        }
                    }
                    if (!empty($lproduct['options'])) {
                        foreach ($lproduct['options'] as $koptions => $voptions) {
                            $aoptions = array();
                            $aoptions['name'] = $voptions['name'];
                            if (!empty($voptions['values'])) {
                                $aoptions['values'] = implode(',', $voptions['values']);
                            }
                            $larr['options'][] = $aoptions;
                        }
                    }
                    if (!empty($lproduct['images'])) {
                        foreach ($lproduct['images'] as $kimages => $vimages) {
                            $aimages = array();
                            $aimages['src'] = $vimages['src'];
                            $larr['images'][] = $aimages;
                        }
                    }
                }
            }
            if (!empty($larr)) {
                $newdata['product'] = $larr;
                $site2 = table('site')
                    ->where('id', $params)
                    ->find();
                $url2 = $site2['site_url'] . "/admin/api/2023-07/products.json";
                $newreturn = posturl($url2, $newdata, $site2);
                if (!empty($newreturn)) {
                    $datareturn = json_decode($newreturn, true);
                    if (isset($datareturn['product']['id']) && !empty($datareturn['product']['id'])) {
                        $msgs = $datareturn['product']['id'];
                    }
                    if (!empty($datareturn['errors'])) {
                        return 'B-'.$datareturn['errors'];
                    }
                }
            }
            return $msgs;
        } else {
            return 4;
        }
    }


    /**
     *  转移商品到新店铺
     */
    //  Tasktransfer/api_orders_transfer?oldid=29&newid=36
    public function api_orders_transfer()
    {
        $site_oldid = $this->request->request('oldid');
        $site_newid = $this->request->request('newid');
        // $where[]  = ['created_at', '>=', 1685548800];
        $where  = array();
        $order = table('order')
            ->where($where)
            ->where('site_id', $site_oldid)
            ->where('transfer_status', 0)
            ->order('transfer_time asc')
            ->limit(30)
            ->select()->toarray();
        $returns = [];
        if (!empty($order)) {
            foreach ($order as $k=>$v) {
                $return = $this->orders_transfer($v, $site_newid);
                $arr['transfer_time'] = time();
                $arr['transfer_status'] = $return;
                $returns[] = table('order')
                    ->where('id', $v['id'])
                    ->update($arr);
            }
        }
        return success('操作完成', $returns);
    }

    public function orders_transfer($orders_shopify, $params)
    {

        $msgs = 3;
        $old_fulfillments = array();
        if (!empty($orders_shopify)) {
            $site = table('site')
                ->where('id', $orders_shopify['site_id'])
                ->find();
            $url = $site['site_url'] . "/admin/api/2023-07/orders/" . $orders_shopify['id'] . ".json";
            $ldata =  geturl($url, $site['apikey'], $site['apisecret']);
            if ($ldata) {
                $ldata2 = json_decode($ldata, true);
                if (!empty($ldata2['errors'])) {
                    return 'A-'.$ldata2['errors'];
                }
                if (!empty($ldata2['order'])) {
                    $ldata2['order']['name'] = str_replace("#","",$ldata2['order']['name']);
                    $ldata2['order']['name'] = '#0'.$ldata2['order']['name'];
                    $ldata2['order']['po_number'] = 1;
                    if(empty($ldata2['order']['tags'])){
                        unset($ldata2['order']['tags']);
                    }
                    // unset($ldata2['order']['customer']);
                    // unset($ldata2['order']['shipping_address']);
                    // unset($ldata2['order']['billing_address']);
                    unset($ldata2['order']['source_name']);
                    // unset($ldata2['order']['contact_email']);
                    // unset($ldata2['order']['email']);
                    if(isset($ldata2['order']['fulfillments'][0]) && !empty($ldata2['order']['fulfillments'][0])){
                        $old_fulfillments = $ldata2['order']['fulfillments'][0];
                        unset($ldata2['order']['fulfillments']);
                    }
                    
                    
                    $ldata2['order']['current_subtotal_price'] = (float)number_format($ldata2['order']['current_subtotal_price']*4, 3, '.', '');
                    $ldata2['order']['current_total_price'] = (float)number_format($ldata2['order']['current_total_price']*4, 3, '.', '');
                    $ldata2['order']['subtotal_price'] = (float)number_format($ldata2['order']['subtotal_price']*4, 3, '.', '');
                    $ldata2['order']['total_line_items_price'] = (float)number_format($ldata2['order']['total_line_items_price']*4, 3, '.', '');
                    $ldata2['order']['total_price'] = (float)number_format($ldata2['order']['total_price']*4, 3, '.', '');
                    if(isset($ldata2['order']['line_items'][0]['price']) && !empty($ldata2['order']['line_items'][0]['price'])){
                        $ldata2['order']['line_items'][0]['price'] = (float)number_format($ldata2['order']['line_items'][0]['price']*4, 3, '.', '');
                    }
                    if(isset($ldata2['order']['current_total_price_set']['shop_money']['amount']) && !empty($ldata2['order']['current_total_price_set']['shop_money']['amount'])){
                        $ldata2['order']['current_total_price_set']['shop_money']['amount'] = (float)number_format($ldata2['order']['current_total_price_set']['shop_money']['amount']*4, 3, '.', '');
                    }
                    if(isset($ldata2['order']['current_total_price_set']['presentment_money']['amount']) && !empty($ldata2['order']['current_total_price_set']['presentment_money']['amount'])){
                        $ldata2['order']['current_total_price_set']['presentment_money']['amount'] = (float)number_format($ldata2['order']['current_total_price_set']['presentment_money']['amount']*4, 3, '.', '');
                    }
                     if(isset($ldata2['order']['total_price_set']['shop_money']['amount']) && !empty($ldata2['order']['total_price_set']['shop_money']['amount'])){
                        $ldata2['order']['total_price_set']['shop_money']['amount'] = (float)number_format($ldata2['order']['total_price_set']['shop_money']['amount']*4, 3, '.', '');
                    }
                    if(isset($ldata2['order']['total_price_set']['presentment_money']['amount']) && !empty($ldata2['order']['total_price_set']['presentment_money']['amount'])){
                        $ldata2['order']['total_price_set']['presentment_money']['amount'] = (float)number_format($ldata2['order']['total_price_set']['presentment_money']['amount']*4, 3, '.', '');
                    }
                    //   halt($ldata2);
                    $site2 = table('site')
                        ->where('id', $params)
                        ->find();
                    $url2 = $site2['site_url'] . "/admin/api/2023-07/orders.json";
                    $newreturn = posturl($url2, $ldata2, $site2);
                    if (!empty($newreturn)) {
                        $datareturn = json_decode($newreturn, true);
                        if (isset($datareturn['order']['id']) && !empty($datareturn['order']['id'])) {
                                //创建物流信息
                                if(!empty($old_fulfillments && isset($datareturn['order']['fulfillments'][0]) && !empty($datareturn['order']['fulfillments'][0]))){
                                    $url_fulfillment = $site2['site_url'] . "/admin/api/2023-07/fulfillments/".$datareturn['order']['fulfillments'][0]['id']."/update_tracking.json";

                                    $data_fulfillments3['notify_customer'] = false;
                                    $data_fulfillments3['tracking_info']['company'] = $old_fulfillments['tracking_company'];
                                    $data_fulfillments3['tracking_info']['number'] = $old_fulfillments['tracking_number'];
                                    $data_fulfillments['fulfillment'] = $data_fulfillments3;
                                    posturl($url_fulfillment,$data_fulfillments, $site2);
                                }
                                
                            $msgs = $datareturn['order']['id'];
                        }else{
                            return 'B-'.$newreturn;
                        }
                    }
                }
            }
            return $msgs;
        } else {
            return 4;
        }
    }

}
